package com.dwzlab.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dwzlab.test.DwzjsonTool;
import com.dwzlab.vo.XUser;
import com.google.gson.Gson;

/**
 * @author zhuxiaodong
 *
 */
public class SubtableAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		@SuppressWarnings("unchecked")
		Enumeration<String> e = request.getParameterNames();
		List<String> filenames = new ArrayList<String>();
		List<String> e_names = new ArrayList<String>();
		List<String> e_ids = new ArrayList<String>();
		while(e.hasMoreElements()){
			String str = e.nextElement();
//			System.out.println(str);
			if(Pattern.matches("^user\\[\\d+\\]\\.id$", str)){
				e_ids.add(str);
			}
			if(Pattern.matches("^x\\[\\d\\]\\.fileName$", str)){
				filenames.add(str);
			}
			if(Pattern.matches("^user\\[\\d+\\]\\.e_name$", str)){
				e_names.add(str);
			}
		}
		Collections.sort(filenames);
		Collections.sort(e_names);
		Collections.sort(e_ids);
//		System.out.println("filenames: " + filenames);
//		System.out.println("e_ids: " + e_ids);
//		System.out.println("e_names: " + e_names);
		List<XUser> xUsers = new ArrayList<XUser>();
		for(int i=0;i<e_ids.size();i++){
			XUser xUser = new XUser();
			xUser.setId(Integer.parseInt(request.getParameter(e_ids.get(i))));
			xUser.setE_name(request.getParameter(e_names.get(i)));
			xUsers.add(xUser);
			System.out.println(request.getParameter(filenames.get(i)));
		}
		System.out.println(xUsers);
		
		response.getWriter().write(new Gson().toJson(DwzjsonTool.newInstance().initDwzjson("200", "KO", "dialog1", "", "", "")));
	}
}
